#!/usr/bin/env node
/***
 * 直接运行 node gitPush.js 推送代码到gitee 或者 github
 */
const program = require('./_commander@8.3.0/index.js');
const packageJson = require('./package');

function parseListArgv( val ) {
  if ( val ) {
    return val.split( ',' );
  } else {
    return [];
  }
}

program
  .version( packageJson.version, '-v, --version' )
  .option( '-u, --use-version <version-number>', 'Webpack version' )
  .option( '-j, --js-processors <processors>', 'Specify javascript processors', parseListArgv )
  .option( '-s, --style-processors <processors>', 'Specify style(css,image,fonts) processors', parseListArgv )
  .option( '--no-install', 'Do not install devDependncies package' )
  .parse( process.argv );

const { exec } = require('child_process');
let commentArg = process.argv.slice(2)[0];
exec('git status', { shell: process.platform === 'win32' }, (error, stdout, stderr) => {
    if (error) {
        console.error(`执行出错: ${error}`);
        return;
    }
    console.log('status： ok',stdout)
   
    let result = stdout;
    // 只取修改了的和增加的文件，字符串分割
    if(stdout.includes('Changes not staged for commit:')) {
        result = stdout.split('Changes not staged for commit:')[1];
    }
    //   console.log(`stdout: ${stdout}`);
    let fileList = result.match(/\t+.+[\n]/g)?.map((item) => {
        // 八进制转中文
        item = Octal2Chinese(item);
        item = item.replace('modified:', '');
        item = item.replace('deleted:', '');
        console.log(Octal2Chinese(item))
        // item = item.replace(/["]/g,'');
        return item.replace(/(\s)/g, '');
    }).filter((item) => {
        // 排除 vscode svn git文件夹
        return !item.includes('.svn/') && !item.includes('.git/') && !item.includes('.vscode/') && !item.includes('node_modules') && !item.includes('newfile:')
    });
    let file = fileList?.join(' ');
    console.log("添加的文件：",`git add ${file}`)
    if (!file) return
    if (stderr) {
        console.error(`stderr: ${stderr}`);
        return
    }
    exec(`git add ${file}`, { shell: process.platform === 'win32' }, (error, stdout, stderr) => {
        if (error) {
            console.error(`执行出错: ${error}`);
            return;
        }
        console.log('添加成功 stdout：', stdout)
        if (stderr) {
            console.error(`stderr： ${stderr}`);
        }
        // 有注释就写注释没注释写时间
        let comment = new Date().format('yyyy-MM-dd hh:mm:ss');
        exec(`git commit -m "${commentArg ? commentArg : comment}"`, (error, stdout, stderr) => {
            if (error) {
                console.error(`执行出错： ${error}`);
                return;
            }
            console.log('commit成功 stdout：', stdout)
            if (stderr) {
                console.error(`stderr： ${stderr}`);
            }
            push();
        });
    })
});

// 防止 push 失败
function push() {
    exec(`git push -u origin master`, (error, stdout, stderr) => {
        if (error) {
            console.error(`执行出错： ${error}`);
            push();//递归
            return;
        }

        console.log('push成功 stdout：', stdout);
        if (stderr) {
            console.error(`stderr： ${stderr}`);
        }
    });
}

// 八进制转 中文
function Octal2Chinese(str) {
    const matches = str.match(/(\\\d{3}){3}/g);
    if (matches) matches.forEach(match => {
      let encoded = '';
      const splits = match.split('\\');
      splits.forEach(code => !code || (encoded += '%' + parseInt(code, 8).toString(16)));
      const cChar = decodeURI(encoded);
      str = str.replace(match, cChar);
    });
    return str;
  }
Date.prototype.format = function (fmt) { //author: meizz   
    var o = {
        "M+": this.getMonth() + 1,                 //月份   
        "d+": this.getDate(),                    //日   
        "h+": this.getHours(),                   //小时   
        "m+": this.getMinutes(),                 //分   
        "s+": this.getSeconds(),                 //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}